package com.turing.post.tuxedo.service;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.organization.util.Merchant;
import com.turing.post.organization.util.MerchantBusinessType;
import com.turing.post.organization.util.MerchantBusinessTypeDao;
import com.turing.post.organization.util.MerchantDao;
import com.turing.post.transaction.util.TranApplicationException;
import com.turing.post.tuxedo.util.IBSType;
import com.turing.post.tuxedo.util.LocalService;
import com.turing.post.tuxedo.util.LocalServiceImpl;
import com.turing.post.tuxedo.util.OBSType;
import com.turing.post.tuxedo.util.PCPSService;
import com.turing.post.tuxedo.util.TransRequest;
import com.turing.post.tuxedo.util.TransResponse;
import com.turing.post.tuxedo.util.TuxedoRespCode;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

@Stateless(mappedName = "PCPS.SVC9088")
@Remote( { LocalService.class, PCPSService.class })
@Local
public class BsType extends LocalServiceImpl implements LocalService,
		PCPSService {

	@EJB(mappedName = "organization.impl.MerchantDaoImpl")
	private MerchantDao merchantDaoImpl;

	@EJB(mappedName = "organization.impl.MerchantBusinessTypeDaoImpl")
	private MerchantBusinessTypeDao merchantBusinessTypeDaoImpl;

	/**
	 * generate IBSType
	 * 
	 * @return IBSType
	 */
	public IBSType makeRequestObject() {
		return new IBSType();
	}

	/**
	 * BSType 数据检查
	 * 
	 * @param req
	 * @param ack
	 */
	protected void preService(TransRequest req, TransResponse ack)
			throws PCPSApplicationException {
	}

	/**
	 * BSType service entry 下载数据字典的业务逻辑
	 * 
	 * @param req
	 * @param ack
	 */
	protected void Service(TransRequest req, TransResponse ack)
			throws PCPSApplicationException {

		IBSType itr = (IBSType) req;
		OBSType otr = (OBSType) ack;

		otr.allbs.clear();

		// 如果商户号无效或者该商户消费时无需业务类型则直接返回
		Merchant merchant = merchantDaoImpl
				.getMerchantByMerchantNo(itr.merchantNo);
		if (merchant == null
				|| !PCPSUtil.compareObject(merchant.getNeedBusinessType(),
						Merchant.BUSINESSTYPE_NEED))
			return;

		// 查询商户定义的业务类型
		List<MerchantBusinessType> mbstypelist = merchantBusinessTypeDaoImpl
				.getAllMerchantBusinessTypeByMerchantNo(itr.merchantNo);

		if (mbstypelist == null || mbstypelist.size() < 1)
			return;

		for (MerchantBusinessType mbt : mbstypelist)
			otr.allbs.put(mbt.getBusinessType(), mbt.getBusinessName());

		if (otr.allbs.size() > 30)
			throw new TranApplicationException(TuxedoRespCode.RC_DBERR,
					"太多的业务类型!");

		// 成功返回
		otr.respCode = TransResponse.RESPCODE_SUCC;
	}

	/**
	 * BSType 服务入口
	 * 
	 * @param req
	 * @return TransResponse
	 */
	public TransResponse Service(TransRequest req)
			throws PCPSApplicationException {
		// 按普通方法执行服务
		return CommonService(req, new OBSType());
	}
}